﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ciripescu_WebRole.BL;
using Ciripescu_WebRole.Entities;
using Microsoft.WindowsAzure.Diagnostics.Management;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.StorageClient;

namespace Ciripescu_WebRole.Admin
{
    public partial class user_admin : AdminBasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {               
                GroupIdListB.Items.Add(new ListItem("Normal User", ((int)UserGroup.NormalUser).ToString()));
                GroupIdListB.Items.Add(new ListItem("Admin", ((int)UserGroup.Admin).ToString()));
            }
            else
            {
                mesaje.InnerHtml = "";
            }
        }
        protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
        {
            //Add CSS class on header row.
            if (e.Row.RowType == DataControlRowType.Header)
                e.Row.CssClass = "header";

            //Add CSS class on normal row.
            if (e.Row.RowType == DataControlRowType.DataRow &&
                      e.Row.RowState == DataControlRowState.Normal)
                e.Row.CssClass = "normal";

            //Add CSS class on alternate row.
            if (e.Row.RowType == DataControlRowType.DataRow &&
                      e.Row.RowState == DataControlRowState.Alternate)
                e.Row.CssClass = "alternate";
        }

        protected void ResetButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("manage_users.aspx");
        }

        
        

        protected void btnSearchByUser_Click(object sender, EventArgs e)
        {
            UserManager um = new UserManager();
            UsersGridView.DataSource = um.GetItemsByPartialUserName(UserNameT.Text, contains.Checked);
            UsersGridView.DataBind();
        }

       

        #region Copy Logs
        protected void btnCopyLogs_Click(object sender, EventArgs e)
        {
            pushLogs(DataBufferName.Logs, PushAge.Text);
        }

        private void pushLogs(DataBufferName bufferName, string age)
        {
            if (IsTransferInProgress())
            {
                TransferErrorMessage.Text = "Another transfer is in progress. Please wait for this transfer to complete before requesting another.";
                TransferErrorMessage.Visible = true;

                return;
            }

            var queueName = "hellofabric-" + Guid.NewGuid().ToString().ToLowerInvariant();

            var manager = new DeploymentDiagnosticManager(RoleEnvironment.GetConfigurationSettingValue("DiagnosticsConnectionString"),
                                                           RoleEnvironment.DeploymentId);
            foreach (var role in manager.GetRoleNames())
            {
                foreach (var instanceManager in manager.GetRoleInstanceDiagnosticManagersForRole(role))
                {
                    var guid = instanceManager.BeginOnDemandTransfer(bufferName, getTransferParameters(age, queueName));
                    System.Diagnostics.Trace.WriteLine(string.Format("data transfer started for role {0}...", role));
                }
            }

            TransferProgressPanel.Visible = true;
            TransferSetupPanel.Visible = false;
        }

        public void TransferProgressTimer_Tick(object sender, EventArgs e)
        {
            // determine whether any jobs are still running
            if (IsTransferInProgress())
            {
                TransferProgressPanel.Visible = true;
                TransferSetupPanel.Visible = false;
            }
            else
            {
                TransferProgressPanel.Visible = false;
                TransferSetupPanel.Visible = true;
                TransferErrorMessage.Visible = false;
            }
        }

        private bool IsTransferInProgress()
        {
            DeploymentDiagnosticManager manager = null;
            try
            {
                string dcom = RoleEnvironment.GetConfigurationSettingValue("DiagnosticsConnectionString");
                string id = RoleEnvironment.DeploymentId;

                manager = new DeploymentDiagnosticManager(dcom, id);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError(ex.ToString());
                return false;
            }

            var account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("DiagnosticsConnectionString"));
            var queueClient = account.CreateCloudQueueClient();

            var result = false;
            var activeTransfers = new Dictionary<string, List<OnDemandTransferInfo>>();

            foreach (var role in manager.GetRoleNames())
            {
                foreach (var instanceManager in manager.GetRoleInstanceDiagnosticManagersForRole(role))
                {
                    var transfers = instanceManager.GetActiveTransfers();

                    foreach (var transfer in transfers)
                    {
                        if (!activeTransfers.ContainsKey(transfer.Value.NotificationQueueName))
                            activeTransfers.Add(transfer.Value.NotificationQueueName, new List<OnDemandTransferInfo>());

                        activeTransfers[transfer.Value.NotificationQueueName].Add(transfer.Value);
                    }
                }
            }

            foreach (var queueTransfersPair in activeTransfers)
            {
                var queue = queueClient.GetQueueReference(queueTransfersPair.Key);

                if (queue.Exists())
                {
                    foreach (var msg in queue.GetMessages(queueTransfersPair.Value.Count))
                    {
                        var info = OnDemandTransferInfo.FromQueueMessage(msg);
                        var instanceManager = manager.GetRoleInstanceDiagnosticManager(info.RoleName, info.RoleInstanceId);
                        var res = instanceManager.EndOnDemandTransfer(info.RequestId);
                        System.Diagnostics.Trace.WriteLine(string.Format("data transfer complete for role instance {0}.", info.RoleInstanceId));

                        var pairInfo = queueTransfersPair.Value.Find((value) => value.RequestId == info.RequestId);

                        if (pairInfo != null)
                            queueTransfersPair.Value.Remove(pairInfo);

                        queue.DeleteMessage(msg);
                    }
                }

                if (queueTransfersPair.Value.Count != 0)
                    result = true;
                else if (queue.Exists())
                    queue.Delete();
            }

            return result;
        }
        private OnDemandTransferOptions getTransferParameters(string age, string notificationQueueName)
        {
            return new OnDemandTransferOptions()
            {
                LogLevelFilter = (LogLevel)Enum.Parse(typeof(LogLevel), PushLevel.SelectedValue),
                From = DateTime.Now.Subtract(TimeSpan.FromMinutes(Int32.Parse(age))),
                To = DateTime.Now,
                NotificationQueueName = notificationQueueName
            };
        }
        #endregion

        protected void btnCopyDirectories_Click(object sender, EventArgs e)
        {
            pushLogs(DataBufferName.Directories, PushAge.Text);
        }

        protected void btnSendTestEmail_Click(object sender, EventArgs e)
        {
            
            MailQueue mq = new MailQueue();
            mq.SendWelcomeMessage(txtTestEmail.Text, "Test email from admin interface");
            mq.SendInvitation("test", txtTestEmail.Text, "test", "ciripescu@ciripescu.ro");
            mq.SendResetPassMail(txtTestEmail.Text, "test", "blabla");

            Random r = new Random();
            lblEmailSended.Text = "3 messages sent! " + "random verification number: " + r.Next(int.MaxValue);
        }
    }
}
